package thread;

import java.util.Random;
import java.util.concurrent.Semaphore;

/**
 * @Author: Administrator
 * @Date: 2023/2/14 17:12
 */

public class SemophreExample {
    static Random random = new Random();

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(10);
        for (int i = 0; i < 50; i++) {
            new Thread(new Car(semaphore, i)).start();
        }
    }

    static class Car extends Thread {
        Semaphore semaphore;
        int id;

        public Car(Semaphore semaphore, int id) {
            this.semaphore = semaphore;
            this.id = id;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
                System.out.println("第" + id + "辆进来了");
                Thread.sleep(random.nextInt(5000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
                System.out.println("第" + id + "辆走了");
            }

        }
    }
}

